package scatter.interview.rest.interview.i1_queue;

/**
 * 循环队列，不浪费空间
 * Created by yangwei
 * Created at 2020/12/2 15:53
 */
public class CircleQueue<T> extends AbstractQuene<Integer,Integer,T>{

    private Object[] data;


    /**
     * 构造
     */
    public CircleQueue(Integer size) {
        this.rear = 0;//队尾为0
        this.front = 0;//队首为0
        data = new Object[size];
        this.size = size;
    }

    //两个状态:队空&队满
    public boolean isNull() {
        return this.front.equals(this.rear) ;
    }

    public boolean isFull() {
        if ((rear + 1) % this.size == front) {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 入队
     *
     * @return boolean
     */
    @Override
    public boolean push(T t) {
        if (isFull()){
            return false;//队满则无法进队
        }
        else {
            data[rear] = t;//进队
            rear = (rear + 1) % size;//队尾指针+1.
            return true;
        }
    }

    /**
     * 出队
     *
     * @return t 队首元素
     */
    @Override
    public T pop() {
        if (isNull()){
            return null;//对空无法出队
        }
        else {
            T popData = (T) data[front++];//出队
            front = (front) % size;//队头指针+1
            return popData;
        }
    }

    public static void main(String[] args) {
        CircleQueue<String> sQueue = new CircleQueue<>(10);
        sQueue.push("1");
        sQueue.push("2");
        sQueue.push("3");
        sQueue.push("4");
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        sQueue.push("1");
        sQueue.push("2");
        sQueue.push("3");
        sQueue.push("4");
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        sQueue.push("1");
        sQueue.push("2");
        sQueue.push("3");
        sQueue.push("4");
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
    }
}
